// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace SnapObjects.Data.AspNetCore
{
    internal class ModelBinder : IModelBinder
    {
        private readonly IDataFormater _dataFromater;

        public ModelBinder(IDataFormater dataFormater)
        {
            _dataFromater = dataFormater;
        }

        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var request = bindingContext.HttpContext.Request;
            
            try
            {
                request.EnableBuffering();

                var model = await _dataFromater
                    .FormatAsync(request, bindingContext.ModelType, default);

                bindingContext.Result = ModelBindingResult.Success(model);
            }
            catch (Exception ex)
            {
                bindingContext.Result = ModelBindingResult.Failed();

                bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, ex.Message);
            }
            finally
            {
                request.Body.Position = 0;
            }
        }
    }
}
